<template>
  <div class="cpSet all scroolBar " style="overflow-y: auto;">
    <!-- 筛选组件-->
    <div>
      <el-button type="primary" @click="openDialog"> 新增CP类型</el-button>
    </div>

    <!-- 表格组件-->
    <div>
      <myTable :tabelHeader="tableHeader" :tableData="cpList" @tableCellClick="onMoudelMsg"></myTable>
    </div>
    <!-- 分页组件 -->
    <div class="workCenterRig">
      <table-paper :currPageNum="pageNum" :PagerOrder="PagerOrder"  @tablePaperEven="onMoudelMsg"  ></table-paper>
    </div>

    <!-- 对话框组件-->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      @close="handleClose">
      <div class="w90">
        <el-form ref="form" :model="form" label-width="100px">

          <el-form-item label="CP名称">
            <el-input v-model="form.name"></el-input>
          </el-form-item>

          <el-form-item label="上传图标">
            <el-upload
              class="avatar-uploader"
              :action="actionUrl"
              :data="actionData"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :http-request="http">
              <img v-if="form.url" :src="form.url" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>

          <el-form-item label="CP状态">
            <el-switch
              v-model="form.status"
              active-text="启用"
              inactive-text="停用"
              active-value="1"
              inactive-value="0">
            </el-switch>
          </el-form-item>

          <el-form-item label="CP资产值">
            <el-input type="number" v-model="form.money"></el-input>
          </el-form-item>

        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="confirmDialog">确 定</el-button>
  </span>
    </el-dialog>

  </div>

  </div>
</template>

<script>
  import myTable from './../../components/yqq/table'
  import tablePaper from '../../components/yqq/tablePaper'
  import {
    getCpSetList,
    postAddCpSet,
    getCpSetInfo,
    deleteCpSet,
    putRefleshCpSet,
    upload
  } from './api'
  import Cookies from 'js-cookie'
  var  adminName=Cookies.get('adminName')
  var  token=Cookies.get('token')
  export default {
    name: "cpSet",
    components: {
      "myTable":myTable,
      tablePaper,
    },
    data(){
      return{
        form:{
          name:'', // |name |string |等级名称 |
          url:'',// |url |string |图片路径 |
          status:'1',// |status |char |启用状态(0-停用1-启用) |
          money:0.00// |money |double |资产值 |
        },
        actionUrl:'',
        headers:{
          "Content-Type":"application/json"
        },
        actionData:{
          adminName:adminName,
          token:token
        },
        title:"提示", //对话框标题
        dialogVisible:false,//对话框展示
        pageNum:1,//页码
        pageSize:10,//个数
        PagerOrder:{
          count:0,
        },
        cpList:[],//cp列表
        //表头数据
        tableHeader:[
          {
            type: 'image',
            key: 'url',
            value: '图标路径',
            canClick:'0',
            iconSize:'40px'
          }, {
            type:'text',
            key:'name',
            value:'cp等级名称',
          },
          {
            type:'text',
            key:'statusName',
            value:'状态',
          },
          {
            type: 'button',
            key: 'primary',
            value: '操作',
            btnLis:[
              {
                name:'编辑',
                judeKey:'primary',
                judeValue:'primary',
                type:'edit',
                btntype:'primary',
              },
              {
                name:'删除',
                judeKey:'primary',
                judeValue:'primary',
                type:'delete',
                btntype:'danger',
              }
            ]}],
      }
    },
    created() {
      this.getCpSetList()
    },
    methods:{
      //获取区服列表
      getCpSetList(){
        var getObj = {
          pageNum:this.pageNum,
          pageSize:this.pageSize
        }
        getCpSetList(getObj).then(res=>{
          // console.log("获取cp列表",res)
          if (res.code==0){
            var vdata = res.data.list
            vdata.forEach((items,i)=>{
              items.primary = 'primary' //按钮默认显示
              items.statusName = items.status==0?"停用":"启用"
            })
            this.cpList = vdata
            this.PagerOrder={
              count:res.data.total,
              size:this.pageSize
            }
          }
        }).catch(err=>{
          // console.log(err)
        })
      },

      //表格组件事件
      onMoudelMsg(data){
        // console.log(data)
        let btnType = data.type
        let itemData = data.data

        if(btnType == 'paperNumChange'){
          this.pageNum = itemData
          this.getCpSetList()
        }

        if (btnType=="edit"){

          this.title="编辑CP类型"
          this.dialogVisible=true
          this.form={
            name:itemData.name, // |name |string |等级名称 |
            url:itemData.url,// |url |string |图片路径 |
            status:itemData.status,// |status |char |启用状态(0-停用1-启用) |
            money:itemData.money,// |money |double |资产值 |
            rankId:itemData.rankId
          }
        }


        //
        // if(btnType == 'level'){
        //   this.$router.push({path:'/Head/gameLevel',query:{gameId:itemData.gameId}})
        // }
        if(btnType == 'delete'){
          this.$confirmMsg("确定删除吗？",'','',()=>{
            deleteCpSet({rankId:itemData.rankId}) .then((res)=>{
              if (res.code==0){
                this.$notifyMsg("提示","删除成功！","success")
                this.getCpSetList()
              }else {
                this.$notifyMsg("提示","删除失败!","error")
              }
            })
          },()=>{},)

        }

      },
      //新增对话框
      openDialog(){
        this.title="新增CP类型"
        this.dialogVisible=true
      },
      //对话框关闭
      handleClose(){
        this.form={
          name:'', // |name |string |等级名称 |
          url:'',// |url |string |图片路径 |
          status:'1',// |status |char |启用状态(0-停用1-启用) |
          money:0.00// |money |double |资产值 |
        }
      },
      //对话框确认
      confirmDialog(){
        if (!!!this.form.name){
          this.$notifyMsg("警告","CP等级名称不可为空!","error")
          return
        }else if(!!!this.form.url){
          this.$notifyMsg("警告","CP图标路径不可为空!","error")
          return
        }else if(this.form.money==''&&this.form.money==undefined){
          this.$notifyMsg("警告","CP资产值不可为空!","error")
          return
        }else {
          if(this.form.hasOwnProperty("rankId")){
            putRefleshCpSet(this.form).then(res=>{
              // console.log(res)
              if (res.code==0){
                this.$notifyMsg("提示","更新成功","success")
                this.getCpSetList()
              }
              this.dialogVisible=false
            })
          } else {
            postAddCpSet(this.form).then(res=>{
              // console.log(res)
              if (res.code==0){
                this.$notifyMsg("提示","新增成功","success")
                this.getCpSetList()
              }
              this.dialogVisible=false
            })
          }
        }
      },
      //上传图片事件
      handleAvatarSuccess(res, file) {
        // console.log(res, file)
        // this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        // console.log(file)
        // / 拿到当前上传图片的name，判断其后缀名是否符合
        let type = this.isImage(file.name);
        // console.log(type);
        if (type==true){
          // 利用fileReader对象获取file
          var file = file
          this.base64(file).then(resBase64 => {
            var imgmax=resBase64.split(',')[1]//直接拿到base64信息
            this.actionData.picName = file.name
            this.actionData.img = imgmax

            // console.log(this.actionData)
            upload(this.actionData).then(res=>{
              // console.log('上传图片',res)
              if (res.code==0){
                var imgUrl = res.data.imgUrl
                this.form.url = imgUrl
              }
            })
          })
        }else {
          this.$notifyMsg("警告","图片格式不正确！","error")
        }
      },
      //自定义上传重写
      http(){},
      // 封装一个判断图片文件后缀名的方法
      isImage(fileName) {
        if (typeof fileName !== 'string') return;
        let name = fileName.toLowerCase();
        return name.endsWith('.png') || name.endsWith('.jpeg') || name.endsWith('.jpg') || name.endsWith('.png') || name.endsWith('.bmp');
      },
      //base64
      base64(file){
        return new Promise((resolve, reject) => {
          let reader = new FileReader();
          let fileResult = "";
          reader.readAsDataURL(file);
          //开始转
          reader.onload = function() {
            fileResult = reader.result;
          };
          //转 失败
          reader.onerror = function(error) {
            reject(error);
          };
          //转 结束  咱就 resolve 出去
          reader.onloadend = function() {
            resolve(fileResult);
          };
        });
      },
    }
  }
</script>

<style scoped>
  .cpSet .el-input { width:200px!important;}
  .cpSet .el-input-number{width: auto}
  /*.gameType .el-select { width:200px!important;}*/

  .cpSet::-webkit-scrollbar {
    display: block;
  }
  .cpSet .avatar-uploader .el-upload {
    border: 1px dashed lightgray;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .cpSet .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .cpSet .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .cpSet .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
